package com.bbzn.device.client.controller;

import com.alibaba.fastjson.JSON;
import com.bbzn.device.client.vo.req.SystemParamVO;
import com.bbzn.device.client.constant.PageConstant;
import com.bbzn.device.client.constant.SystemParamConstant;
import com.bbzn.device.client.dataobject.SystemParam;
import com.bbzn.device.client.dto.system.SystemParamDTO;
import com.bbzn.device.client.service.CommonService;
import com.bbzn.device.client.service.SystemParamByCacheService;
import com.bbzn.device.client.service.SystemParamService;
import com.bbzn.device.client.utils.*;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @Author 黄志鹏
 * @Date 2021/3/16 17:11
 * @Version 1.0
 */

@RestController
@RequestMapping("/systemParam")
@Slf4j
@Api(value = "systemParam", tags = "系统参数")
@ApiSort(value = 1)// 大分类顺序
//@CrossOrigin
public class SystemParamController extends BaseApiService {

    @Autowired
    private CommonService commonService;

    @Autowired
    private SystemParamService systemParamService;

    @Autowired
    private SystemParamByCacheService systemParamByCacheService;

    @Autowired
    private RedisUtils<String> redisUtils;

    /**
     * 获取系统参数列表
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "获取系统参数列表", produces = "application/json")
    @ApiOperationSupport(ignoreParameters = {"reqVO.pageNum", "reqVO.pageSize", "reqVO.startIndex"})
    @RequestMapping(value = "/getSystemParamList", method = RequestMethod.POST)
    public BaseResponse getSystemParamList(@RequestBody SystemParamVO reqVO, HttpServletRequest request) throws Exception {
        if (!OptionalBean.ofNullable(reqVO.getPageSize()).isPresent()) {
            reqVO.setPageSize(PageConstant.PAGE_SIZE_APP);
        }
        if (!OptionalBean.ofNullable(reqVO.getPageNum()).isPresent()) {
            reqVO.setPageNum(PageConstant.PAGE_NUM);
        }
        SystemParamDTO systemParamDTO = new SystemParamDTO();
        if (null != reqVO.getPageNum()) {
            systemParamDTO.setPageNum(reqVO.getPageNum());
        }
        if (null != reqVO.getPageSize()) {
            systemParamDTO.setPageSize(reqVO.getPageSize());
        }
        // 模糊查詢
        if (OptionalBean.ofNullable(reqVO.getType()).isPresent()) {
            systemParamDTO.setType(reqVO.getType());
        }
        if (OptionalBean.ofNullable(reqVO.getValue()).isPresent()) {
            systemParamDTO.setValue(reqVO.getValue());
        }
        if (OptionalBean.ofNullable(reqVO.getMassage()).isPresent()) {
            systemParamDTO.setMassage(reqVO.getMassage());
        }
        systemParamDTO.setStartIndex((reqVO.getPageNum() - 1) * reqVO.getPageSize());

        PageInfo<SystemParam> systemParamList = systemParamService.selectPageSelective(systemParamDTO);
        return setResultSuccess(systemParamList);
    }


    /**
     * 添加系统参数
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "添加系统参数", produces = "application/json")
    @ApiOperationSupport(ignoreParameters = {"reqVO.pageNum", "reqVO.pageSize", "reqVO.startIndex"})
    @RequestMapping(value = "/addSystemParam", method = RequestMethod.POST)
    public BaseResponse addSystemParam(@RequestBody SystemParamVO reqVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commonService.getUserId(request);
        String userName = MayiktJwtUtils.getUsername(request, secretKey);

        if (!OptionalBean.ofNullable(reqVO.getType()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(SystemParamConstant.SYSTEM_PARAM_ENUM, SystemParamConstant.SYSTEMPARAM_NO_TYPE_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getKey()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(SystemParamConstant.SYSTEM_PARAM_ENUM, SystemParamConstant.SYSTEMPARAM_NO_KEY_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getValue()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(SystemParamConstant.SYSTEM_PARAM_ENUM, SystemParamConstant.SYSTEMPARAM_NO_VALUE_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getMassage()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(SystemParamConstant.SYSTEM_PARAM_ENUM, SystemParamConstant.SYSTEMPARAM_NO_MASSAGE_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }

        SystemParam addSysParam = new SystemParam();
        addSysParam.setType(reqVO.getType());
        addSysParam.setKey(reqVO.getKey());
        addSysParam.setValue(reqVO.getValue());
        addSysParam.setMassage(reqVO.getMassage());
        addSysParam.setCreateTime(new Date());
        addSysParam.setUpdateTime(new Date());
        addSysParam.setCreateBy(userName);
        systemParamService.insert(addSysParam);
        systemParam = systemParamByCacheService.getValues(SystemParamConstant.SYSTEM_PARAM_ENUM, SystemParamConstant.SYSTEMPARAM_ADD_SUCCESS_PREFIX + language);
        return setResultSuccess();
    }

    /**
     * 修改系统参数
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "修改系统参数", produces = "application/json")
    @ApiOperationSupport(ignoreParameters = {"reqVO.pageNum", "reqVO.pageSize", "reqVO.startIndex"})
    @RequestMapping(value = "/updateSystemParam", method = RequestMethod.POST)
    public BaseResponse updateSystemParam(@RequestBody SystemParamVO reqVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commonService.getUserId(request);
        String userName = MayiktJwtUtils.getUsername(request, secretKey);
        if (!OptionalBean.ofNullable(reqVO.getId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(SystemParamConstant.SYSTEM_PARAM_ENUM, SystemParamConstant.SYSTEMPARAM_NO_ID_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }

        if (!OptionalBean.ofNullable(reqVO.getType()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(SystemParamConstant.SYSTEM_PARAM_ENUM, SystemParamConstant.SYSTEMPARAM_NO_TYPE_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getKey()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(SystemParamConstant.SYSTEM_PARAM_ENUM, SystemParamConstant.SYSTEMPARAM_NO_KEY_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getValue()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(SystemParamConstant.SYSTEM_PARAM_ENUM, SystemParamConstant.SYSTEMPARAM_NO_VALUE_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }
        if (!OptionalBean.ofNullable(reqVO.getMassage()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(SystemParamConstant.SYSTEM_PARAM_ENUM, SystemParamConstant.SYSTEMPARAM_NO_MASSAGE_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }

        SystemParam updateSysParam = BabaBeanUtils.voToDto(reqVO, SystemParam.class);
        updateSysParam.setUpdateTime(new Date());
        updateSysParam.setUpdateBy(userName);
        boolean hExists = redisUtils.hExists(reqVO.getType(), reqVO.getKey());
        //存在修改Redis中的数据
        if (hExists) {
            redisUtils.hPut(reqVO.getType(), reqVO.getKey(), JSON.toJSONString(updateSysParam));
        }
        systemParamService.updateByPrimaryKeySelective(updateSysParam);
        systemParam = systemParamByCacheService.getValues(SystemParamConstant.SYSTEM_PARAM_ENUM, SystemParamConstant.SYSTEMPARAM_UPDATE_SUCCESS_PREFIX + language);
        return setResultSuccess();
    }

    /**
     * 删除系统参数
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "删除系统参数", produces = "application/json")
    @ApiOperationSupport(ignoreParameters = {"reqVO.pageNum", "reqVO.pageSize", "reqVO.startIndex"})
    @RequestMapping(value = "/deleteSystemParam", method = RequestMethod.POST)
    public BaseResponse deleteSystemParam(@RequestBody SystemParamVO reqVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commonService.getUserId(request);
        String userName = MayiktJwtUtils.getUsername(request, secretKey);
        if (!OptionalBean.ofNullable(reqVO.getIds()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(SystemParamConstant.SYSTEM_PARAM_ENUM, SystemParamConstant.SYSTEMPARAM_NO_ID_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }

        List<SystemParam> systemParamList = systemParamService.selectBatchIds(reqVO.getIds());
        if (CollectionUtils.isEmpty(systemParamList)) {
            systemParam = systemParamByCacheService.getValues(SystemParamConstant.SYSTEM_PARAM_ENUM, SystemParamConstant.SYSTEMPARAM_NO_DATA_PREFIX + language);
            return setResultError(systemParam.getCode(), systemParam.getMassage());
        }

        systemParamList.stream().forEach(sParam -> {
            boolean hExists = redisUtils.hExists(sParam.getType(), sParam.getKey());
            //存在修改Redis中的数据
            if (hExists) {
                redisUtils.hDelete(sParam.getType(), sParam.getKey());
            }
        });
        systemParamService.deleteBatch(reqVO.getIds());
        systemParam = systemParamByCacheService.getValues(SystemParamConstant.SYSTEM_PARAM_ENUM, SystemParamConstant.SYSTEMPARAM_DELETE_SUCCESS_PREFIX + language);
        return setResultSuccess();
    }

}
